public class l66 {
    public static void main(String[] args) {
        int[] arrays = {6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3};
        
        int[] results = {};
        System.out.println("Origin");
        for (int i=0; i< arrays.length;i++) {
            System.out.print(arrays[i]+",");
        }

        results = plusOne(arrays);
        System.out.println("lenghth="+arrays.length);
        System.out.println("Results");
        System.out.println("lenghth="+results.length);
        for (int i=0; i< results.length;i++) {
            System.out.print(results[i]+",");
        }

    }
    public static int[] plusOne(int[] digits) {
        int last = digits.length - 1;
        if (digits[last] != 9) {

            digits[last]+=1;
        } else {
            int i = last;
            int cnt = 0;
            while (i >= 0) {

                if (digits[i]==9) { 
                    cnt++;
                }
                i--;
            }
            if (cnt == digits.length) { // all 9s, need expand the array
                int[] expand = new int[digits.length+1];
                expand[0] = 1;
                return expand;
            } else { // carry
                i = last;
                while (i>=0 && digits[i]==9) {
                    digits[i]=0;    
                    i--;

                }
                if (i>=0) digits[i]+=1;
                else System.out.println("Error");
            }


        }

        return digits;
        
    }

}
